import z from "zod";

/**
 * ### 单个字段校验
 *
 * @param field - 字段名
 * @param value - 字段值
 * @param shape - 校验规则
 * @returns
 */
export const validByField = <T>(
  field: string,
  value: T,
  shape: z.ZodRawShape
): string => {
  console.log("field=>", field);
  console.log("value=>", value);
  console.log("shape=>", shape);

  const ret = shape[field].safeParse(value);
  console.log("ret error=>", ret);

  if (ret.success) return "";
  return ret.error.format()._errors[0].split(":")[0];
};

/**
 * ### 全部字段校验
 *
 * @param model - 模型对象
 * @param schema - schema对象
 * @param value - 校验值
 */
export const validAll = (
  model: Record<string, IFormModel>,
  schema: Zod.ZodTypeAny
) => {
  const valObj: Record<string, any> = {};
  const keys = Object.keys(model);
  keys.forEach((key) => {
    valObj[key] = model[key].value;
  });

  const ret = schema.safeParse(valObj);
  if (ret.success) return true;
  ret.error.issues.forEach((item) => {
    if (model[item.path[0]])
      model[item.path[0]].ruleMessage = item.message.split(":")[0];
  });
  return false;
};
